<?php
/**
 * Project: shake.com
 * User: xialeistudio
 * Date: 2016/7/15 0015
 * Time: 21:14
 */

namespace app\controllers;


use app\components\ThinkWechat;
use yii\web\Controller;

class WechatController extends Controller
{
    const TOKEN = 'vjjwoM2X95DLyN22_';

    public function actionIndex()
    {
        $wechat = new ThinkWechat(static::TOKEN);
        $data = $wechat->request();
        list($content, $type) = $this->reply($data);

        /* 响应当前请求 */
        $wechat->response($content, $type);
    }

    private function logger($data)
    {
        \Yii::error(printf($data, true), 'wechat');
    }

    private function reply($data)
    {
        $this->logger($data);
        if ($data['MsgType'] == 'event' && $data['Event'] == 'subscribe') {
            return $this->sendShakeNews($data);
        }
        if ($data['MsgType'] == 'text' && $data['Content'] == 'shake') {
            return $this->sendShakeNews($data);
        }
        if ($data['MsgType'] == 'event' && $data['Event'] == 'CLICK') {
            return $this->handleMenuClick($data);
        }
        return ['欢迎关注摇一摇', 'transfer_customer_service'];
    }

    private function sendShakeNews($data)
    {
        $news1 = [
            '欢迎关注疯狂摇',
            '参与“远洋恒利”为庆祝新品上线举行的回馈新老客户送“原始股”摇奖活动。百分百中奖等你来拿！',
            'http://7xthiz.com1.z0.glb.clouddn.com/shake-1.jpg',
            'http://www.588598.xin/#/shake-splash'
        ];
        return [[$news1], 'news'];
    }

    private function handleMenuClick($data)
    {
        if ($data['EventKey'] == 'service') {
            return ['点击左下角键盘可直接与客服交流', 'text'];
        }
        return $this->sendShakeNews($data);
    }

    public function actionAccesstoken()
    {
        return \Yii::$app->wechat->getAccessToken();
    }
}